<?php

namespace App\Clients\Yisheng;

use App\Clients\BaseClient;
use App\Clients\JinShouFu\JinShouFuClient;
use App\Services\JinShouFuHelper;
use Exception;
use GuzzleHttp\Client;
use Psr\Http\Message\ResponseInterface;

abstract class YishengClient extends JinShouFuClient
{

    public function login(): void{
        $response = file_get_contents("https://b2b.eycard.cn/api/code");
        $response = json_decode($response,true);
        $image = $response["data"]["img"];
        $uuid = $response["data"]["uuid"];
        $url = "http://api.jfbym.com/api/YmServer/customApi";
        $client = new Client(["verify"=>false]);
        $image = explode(",",$image);
        $postData = [
            "image"=>$image[1],
            "token"=>"y0nQmzwVzS/2u3NcJSfxx1FfImDTnKIw8HdpdytLZYc",
            "type"=>"50100",
        ];
        $response = $client->post($url,["json"=>$postData])->getBody()->getContents();
        $response = json_decode($response,true);
        $codeNum = $response["data"]["data"];
        $helper = new JinShouFuHelper;
        $key = $helper->setKey("MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANL378k3RiZHWx5AfJqdH9xRNBmD9wGD\n2iRe41HdTNF8RUhNnHit5NpMNtGL0NPTSSpPjjI1kJfVorRvaQerUgkCAwEAAQ==");
        $password = $helper->encrypt($this->account->password,$key);
        $postData = [
            "username"=>$this->account->name,
            "password"=>$password,
            "grant_type"=>"password",
            "code"=>$codeNum,
            "uuid"=>$uuid,
            "client_id"=>"web",
            "client_secret"=>"123456",
            "scope"=>"server",
        ];
        $url = "https://b2b.eycard.cn/api/auth/oauth/token?".http_build_query($postData);
        $response = $client->post($url,["json"=>[]])->getBody()->getContents();
        $response = json_decode($response,true);
        unset($response["user_info"]["roles"]);
        $this->account->cookies = json_encode($response);
        $this->account->login_status = 1;
        $this->account->logout_at = date("Y-m-d H:i:s",time() + 86400);
        $this->account->save();
    }

    public function headers($other = []): array
    {
        $cookies = json_decode($this->account->cookies,true);
        $headers = [
            "User-Agent"=>'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.9 Safari/537.36',
            "Authorization"=>"Bearer ".$cookies["access_token"],
            "Company-Id"=>$cookies["user_info"]["mainMerchantId"],
            "Authorization-Token"=>999999,
        ];
        return array_merge($headers,$other);
    }

    protected function isLogout(ResponseInterface $response){
        $content = $response->getBody()->getContents();
        $content = json_decode($content,true);
        if(!empty($content["error"])){
            $this->account->login_status = 0;
            $this->account->save();
            throw new Exception("掉线了");
        }
        return $content;
    }
}
